<template>
  <div>
    <el-form ref="form" inline label-width="80px">
      <el-form-item>
        <el-input v-model="userName" placeholder="用户名"></el-input>
      </el-form-item>
      <el-button type="primary" icon="el-icon-search" @click="getData">查询</el-button>
      <el-button type="reset" @click="clear">清空</el-button>
    </el-form>
    <div>
      <el-button type="primary" size="mini" @click="dialogFormVisible=true">添加</el-button>
      <el-button type="danger" size="mini" :disabled="selectionIds.length===0" @click="deleteUsers">批量删除</el-button>
    </div>
    <el-table :data="userList" style="width: 100%" border @selection-change="handleSelectionChange">>
      <el-table-column type="selection" width="40"></el-table-column>
      <el-table-column type="index" label="序号" width="80"></el-table-column>
      <el-table-column prop="username" label="用户名" width="100"></el-table-column>
      <el-table-column prop="nickName" label="用户昵称"></el-table-column>
      <el-table-column prop="roleName" label="权限列表"></el-table-column>
      <el-table-column prop="gmtCreate" label="创建时间"></el-table-column>
      <el-table-column prop="gmtModified" label="更新时间"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="{row,$index}">
          <el-button type="primary" @click="setUser(row)" icon="el-icon-user-solid" size="mini"></el-button>
          <el-button type="primary" @click="updateUser(row)" icon="el-icon-edit" size="mini"></el-button>&nbsp;&nbsp;
          <el-popconfirm title="确定删除吗？" @onConfirm="deleteOne(row)">
            <el-button type="danger" slot="reference" icon="el-icon-delete" size="mini"></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--分页器-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-sizes="[5, 10, 15]"
      :page-size="limit"
      layout="prev, pager, next, jumper,->,total, sizes"
      :total="total"
    >
    </el-pagination>
    <!--添加/修改用户-->
    <el-dialog :title="userInfo.id?'修改用户':'添加用户'" :visible.sync="dialogFormVisible" :before-close="cancel">
      <el-form :model="addUser" label-width="80px" ref="ruleForm1" :rules="rules" >
        <el-form-item label="用户名" prop="username"  inline>
          <el-input v-model="addUser.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称">
          <el-input v-model="addUser.nickName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="!userInfo.id">
          <el-input v-model="addUser.password" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="addOneUser">确 定</el-button>
      </div>
    </el-dialog>
    <!--设置角色-->
    <el-dialog :title="userInfo.username" :visible.sync="dialogFormVisible1">
      <el-form :model="addUser" inline >
        <el-form-item label="用户名">
          <el-input :value="userInfo.username" disabled></el-input>
        </el-form-item>
        <br>
        <el-form-item label="角色列表">
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          <div style="margin: 15px 0;"></div>
          <el-checkbox-group v-model="userRoleIdList" @change="handleCheckedCitiesChange">
            <el-checkbox v-for="(role,index) in roleList" :label="role.id" :key="index">{{role.roleName}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="doAssign">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: 'index',
  data() {
    return {
      isIndeterminate:false,
      userName: '',
      //分页器属性
      limit: 10,
      total: 100,
      page: 1,
      //用户列表
      userList: [],
      //id数组 批量删除
      selectionIds: [],
      //添加用户
      addUser: {
        nickName: '',
        password: '',
        username: ''
      },
      //修改用户
      userInfo: {},
      //角色列表
      roleList: [],
      checkAll:false,
      //用户已存在的角色列表
      userRoleList:[],
      userRoleIdList:[],
      //是否显示弹窗
      dialogFormVisible: false,
      dialogFormVisible1: false,
      //表单验证
      rules: {
        username: [
          { required: true, message: '请输入用户名啊', trigger: 'blur' },
          { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'change' }
        ],
        password: [
          { required: true, message: '密码啊'}
        ]
      }

    }
  },
  mounted() {
    //获取数据
    this.getData()
  },
  methods: {
    async getData() {
      let res = await this.$API.user.reqUserList(this.page, this.limit,this.userName)
      if (res.code === 20000) {
        this.userList = res.data.items
        this.total = res.data.total
      }
    },
    handleSizeChange(limit) {
      this.limit = limit
      this.getData()
    },
    handleCurrentChange(page) {
      this.page = page
      this.getData()
    },
    //批量选择
    handleSelectionChange(user) {
      this.selectionIds = []
      user.forEach((item) => {
        this.selectionIds.push(item.id)
      })
    },
    //批量删除
    deleteUsers() {
      this.$confirm('确定删除啊').then(async() => {
        let res = await this.$API.user.reqDeleteUsers(this.selectionIds)
        if (res.code === 20000) {
          this.$message('删除成功')
          await this.getData()
        }
      }).catch(()=>{
       this.$message.info('取消删除')
      })
    },
    //删除一个
    async deleteOne(user) {
      let res = await this.$API.user.reqDeleteOneUser(user.id)
      if (res.code === 20000) {
        this.$message({ type: 'success', message: '删除成功' })
        await this.getData()
      } else {
        this.$message({ type: 'danger', message: '删除失败' })
      }
    },
    //增加/修改一个用户
    addOneUser() {
      this.$refs.ruleForm1.validate(async (success)=>{
        if(success){
          if (!this.addUser.id){
            let res = await this.$API.user.reqAddUser(this.addUser)
            if (res.code === 20000) {
              this.$message('添加成功')
              this.dialogFormVisible = false
              this.addUser = this.$options.data().addUser
              await this.getData()
            }
          }else{
            let res = await this.$API.user.reqUpdateUser(this.addUser)
            if (res.code === 20000) {
              this.$message('修改成功')
              this.dialogFormVisible = false
              this.addUser = this.$options.data().addUser
              await this.getData()
            }
          }
        }
      })
    },
    //取消
    cancel(done) {
      this.dialogFormVisible = false
      this.dialogFormVisible1 = false
      Object.assign(this._data,this.$options.data())
      done()
      this.getData()
    },
    //搜索用户
    async searchUser() {
      let res = await this.$API.user.reqSearchUser(this.page, this.limit,this.userName)
      if (res.code === 20000) {
        this.userList = res.data.items
        this.total = res.data.total
      }
    },
    //清空
    clear() {
      this.userName = ''
      this.getData()
    },
    //设置角色
    async setUser(user){
      this.userInfo = user
      //获取角色列表
      let resRole = await this.$API.user.reqRoles()
      if (resRole.code===20000){
        this.roleList = resRole.data.items
      }
      //获取该用户已分配的角色
      let resUser = await this.$API.user.reqUserRole(user.id)
      if (resUser.code===20000){
        this.userRoleList = resUser.data.assignRoles
        this.userRoleList.forEach(item=>{
          this.userRoleIdList.push(item.id)
        })
      }
      this.dialogFormVisible1 = true
    },
    //分配角色
    async doAssign(){
      let res = await this.$API.user.reqDoAssign(this.userInfo.id,this.userRoleIdList)
      if (res.code===20000){
        this.$message.success("成功")
        this.cancel()
        await this.getData()
      }
    },
    //全选
    handleCheckAllChange(val) {
      this.userRoleList = val ? this.roleList : [];
      this.userRoleIdList = []
      this.userRoleList.forEach(item =>{
        this.userRoleIdList.push(item.id)
      })
      this.isIndeterminate = false;
    },
    //选中某一角色
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.roleList.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.roleList.length;
    },
    //修改角色页面
    async updateUser(user){
      this.dialogFormVisible=true
      this.userInfo = user
      this.addUser.id = user.id
      this.addUser.username = user.username
      this.addUser.nickName = user.nickName
    },
  }
}
</script>

<style scoped>

</style>
